package com.frxuexi.department

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.department.intent.DepartIntent
import com.frxuexi.department.viewmodel.DepartViewModel
import com.frxuexi.lib_base.BaseApp
import com.frxuexi.lib_base.RequestType
import com.frxuexi.lib_base.UiState
import com.frxuexi.lib_base.scan.LocalDocEntity
import com.frxuexi.lib_http.Concast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


@Composable
fun LocalDocPage(
    navHostController: NavHostController,
    vm: DepartViewModel = hiltViewModel(),
    scope: CoroutineScope = rememberCoroutineScope()
) {
    var path = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
    var list = remember {
        SnapshotStateList<LocalDocEntity>()
    }

    //选中的文件名
    var checkeName by remember {
        mutableStateOf("")
    }

    var checkePath by remember {
        mutableStateOf("")
    }

    LaunchedEffect(key1 = "", block = {
        scope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess -> {
                        if(it.type==RequestType.LOCAL_FILE){//扫描本地文件
                            if (it.data != null) {
                                Log.i("===成功", it.data.toString())
                            } else {
                                Log.i("===成功", "没有文件")
                            }
                            list.addAll(it.data as Collection<LocalDocEntity>)
                        }else if(it.type==RequestType.UPLOAD_FILE){//上传
                            Log.i("===","上传文件成功")
                            val docPath=Concast.BASE_URL+"/fileDownload?fileName="+checkeName
                            vm.sendIntent(DepartIntent.addDoc(docPath,checkeName))
                        }else if(it.type==RequestType.UPLOAD_ASYNC){
                            Log.i("===","上传成功")
                            ToastUtils.showLong("上传成功")
                            navHostController.popBackStack()
                        }

                    }

                    is UiState.onError -> {
                        Log.i("===", it.msg)
                    }

                    else -> {}
                }
            }
        }
        vm.sendIntent(DepartIntent.getLocalDoc(path!!))
    })

    Column {
        Row(
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .fillMaxWidth()
                .padding(10.dp)
        ) {
            Icon(imageVector = Icons.Default.ArrowBack,
                contentDescription = "",
                modifier = Modifier.clickable {
                    navHostController.popBackStack()
                })
            Text(text = "本地文件选择")
            Text(text = "上传",Modifier.clickable {
                vm.sendIntent(DepartIntent.uploadDoc(checkeName,checkePath))
            })
        }

        LazyColumn(content = {
            items(list) {
                LocalItem(entity = it, checkeName) {
                    checkeName = it.name
                    checkePath=it.path
                }
            }
        })
    }
}

@Composable
fun LocalItem(entity: LocalDocEntity, isChecked: String, onCheck: () -> Unit) {
    //多选
    /*var isChecked by remember {
        mutableStateOf(false)
    }*/
    Row {
        Box(contentAlignment = Alignment.TopEnd, modifier = Modifier.padding(10.dp)) {
            Image(
                painter = painterResource(id = R.drawable.icon3),
                contentDescription = "",
                Modifier.size(60.dp)
            )
            Image(
                painter = painterResource(id = if (isChecked == entity.name) R.drawable.ic_action_check else R.drawable.ic_action_nocheck),
                contentDescription = "",
                Modifier
                    .size(15.dp)
                    .offset(5.dp, -10.dp)
                    .clickable {
                        onCheck()
                    }
            )
        }
        Column(Modifier.height(60.dp), verticalArrangement = Arrangement.SpaceAround) {
            Text(text = entity.name)
            Text(
                text = entity.path,
                fontSize = 12.sp,
                color = Color.Gray,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}
